package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"net/http"
)

const (
	DSN = "root:123456@(127.0.0.1:3306)/gin_class?charset=utf8mb4&parseTime=True&loc=Local"
)

type Todo struct {
	ID     int    `json:"id"`
	Title  string `json:"title"`
	Status bool   `json:"status"`
}

func initDB() *gorm.DB {
	db, err := gorm.Open(mysql.Open(DSN), &gorm.Config{})
	if err != nil {
		fmt.Println("db init failed %v", err)
		recover()
	}
	return db
}

func initDataSource() {
	db := initDB()
	db.AutoMigrate(&Todo{})
}

func add(c *gin.Context) {

	db := initDB()
	var todo Todo
	c.BindJSON(&todo)

	db.Create(&todo)

	c.JSON(http.StatusOK, gin.H{
		"success": true,
	})
}

func upd(c *gin.Context) {
	c.JSON(http.StatusOK, gin.H{
		"success": true,
	})
}

func getOne(c *gin.Context) {
	var tod Todo

	c.JSON(http.StatusOK, gin.H{
		"id":     tod.ID,
		"title":  tod.Title,
		"status": tod.Status,
	})
}

func getList(c *gin.Context) {
	db := initDB()
	var todos []Todo
	if err := db.Find(&todos).Error; err != nil {
		c.JSON(http.StatusOK, gin.H{"success": false})
	}
	c.JSON(http.StatusOK, &todos)
}

func del(c *gin.Context) {
	id := c.Param("id")
	db := initDB()
	db.Where("id = ? ", id).Delete(Todo{})
	c.JSON(http.StatusOK, gin.H{"success": true})

}

func main() {
	r := gin.Default()
	initDataSource()
	r.Static("static", "static")
	r.LoadHTMLGlob("templates/*")

	//起始页
	r.GET("/", func(c *gin.Context) {
		c.HTML(http.StatusOK, "index.html", nil)
	})

	v1Group := r.Group("v1")
	v1Group.POST("/todo", add)

	v1Group.GET("/todo/:id", getOne)

	v1Group.PUT("/todo/:id", upd)
	v1Group.DELETE("/todo/:id", del)

	v1Group.GET("/todo", getList)

	r.Run()
}
